<template>
	<view class="adviserPage bg-fff">
        <canvas :canvas-id="CanvasID" :style="{ width: canvasW + 'px', height: canvasH + 'px' }"></canvas>
        <button class="saveBtn" @click="savePoster">保存图片</button>
	</view>
</template>
<script>
    import { mapState } from 'pinia';
    import { useUserInfoStore, useIndexStore } from '@/store/index';

	export default {
		data() {
			return {
                productId: '',
                userName: '',
                phone: '',
                canvasW: 750,
                canvasH: 1334,
                canvasImgSrc:'',
                ctx:null,
				CanvasID: 'myCanvas',
                imgSrc: 'https://image.srea.org.cn/images/a8ddc674-7759-1a2c-8d68-b369288b5d1a_微信图片_20200219114924.jpg?x-oss-process=style/preview',
                QrSrc: 'https://image.srea.org.cn/xpkf027.jpg',
                headerSrc: 'https://image.srea.org.cn/adviser/9149bae0-08dd-4315-ae81-57c1c6739065',
                Title: '',
                TitleColor: '#333333',
                LineType: true,
                CanvasBg: '#ffffff',
                ViewDetails: '长按或扫描识别二维码'
			}
		},
        computed:{
            ...mapState(useUserInfoStore, ['userInfo']),
            ...mapState(useIndexStore, ['nowCityCode']),
        },
		onLoad(options){
            const that = this;
            let { phone, userName, productTitle, qrcode, prodImage, userHeader } = JSON.parse(decodeURIComponent(options.info));
            this.userName = userName;
            this.phone = phone;
            this.imgSrc = prodImage;
            this.Title = productTitle;
            this.QrSrc = qrcode;
            this.headerSrc = userHeader;
            that.$check_and_login(function () {
                that.OnCanvas();
            })
		},
		methods: {
			async OnCanvas() {
                const _this = this;
                _this.ctx = uni.createCanvasContext(_this.CanvasID,this);
                const C_W = uni.upx2px(_this.canvasW), //canvas宽度
                    C_P = uni.upx2px(30), //canvas Paddng 间距
                    C_Q = uni.upx2px(150); //二维码或太阳码宽高
                let _strlineW = 0; //文本宽度
                let _imgInfo = await _this.getImageInfo({ imgSrc: _this.imgSrc }); //广告图
                let _QrCode = await _this.getImageInfo({ imgSrc: _this.QrSrc }); //二维码或太阳码
                let _userHeader = await _this.getImageInfo({ imgSrc: _this.headerSrc }); //二维码或太阳码
                let r = [_imgInfo.width, _imgInfo.height];
                let q = [_QrCode.width, _QrCode.height];
                let header = [_userHeader.width, _userHeader.height];
                let imgW = C_W - C_P * 2;
                if (r[0] != imgW) {
                    r[1] = Math.floor((imgW / r[0]) * r[1]);
                    r[0] = imgW;
                }
                if (q[0] != C_Q) {
                    q[1] = Math.floor((C_Q / q[0]) * q[1]);
                    q[0] = C_Q;
                }
                if(header[0] != C_Q) {
                    header[1] = Math.floor((C_Q / header[0]) * header[1]);
                    header[0] = C_Q;
                }
                _this.canvasW = C_W;
                _this.canvasH = r[1] + q[1] + 128;
                _this.ctx.setFillStyle(_this.CanvasBg); //canvas背景颜色
                _this.ctx.fillRect(0, 0, C_W, _this.canvasH); //canvas画布大小
                
                //添加图片展示
                _this.ctx.drawImage(_imgInfo.path, C_P, C_P, r[0], r[1]);
                // _this.ctx.drawImage(_imgInfo.path, 0, 0, 750, 300);
                //添加图片展示 end
                //设置文本
                _this.ctx.setFontSize(uni.upx2px(32)); //设置标题字体大小
                _this.ctx.setFillStyle(_this.TitleColor); //设置标题文本颜色
                let _strLastIndex = 0; //每次开始截取的字符串的索引
                let _strHeight = r[1] + C_P * 2 + 10; //绘制字体距离canvas顶部的初始高度
                let _num=1;
                for (let i = 0; i < _this.Title.length; i++) {
                    _strlineW += _this.ctx.measureText(_this.Title[i]).width;
                    if (_strlineW > r[0]) {
                        if(_num == 2&&_this.LineType){
                            //文字换行数量大于二进行省略号处理
                            _this.ctx.fillText(_this.Title.substring(_strLastIndex, i-8)+'...', C_P, _strHeight);
                            _strlineW = 0;
                            _strLastIndex = i;
                            _num++;
                            break;
                        }else{
                            _this.ctx.fillText(_this.Title.substring(_strLastIndex, i), C_P, _strHeight);
                            _strlineW = 0;
                            _strHeight += 20;
                            _strLastIndex = i;
                            _num++;
                        }
                    }
                    if (i == _this.Title.length - 1) {
                        _this.ctx.fillText(_this.Title.substring(_strLastIndex, i + 1), C_P, _strHeight);
                        _strlineW = 0;
                    }
                }
                //添加头像
                _strHeight += uni.upx2px(60);
                // 原理：利用 Canvas 先画出一个圆形，然后将图片定位到圆形中心位置进行剪切，将超出圆形的部分去掉，就会形成一个圆形
                _this.circleImgOne(_this.ctx, _userHeader.path, C_P, _strHeight, 30);
                // _this.ctx.drawImage(_userHeader.path, C_P, _strHeight, header[0], header[1]);
                //添加头像 end
                
                //名字
                _this.ctx.setFillStyle(_this.TitleColor);
                _this.ctx.setFontSize(uni.upx2px(32));
                _this.ctx.fillText(_this.userName, header[0]+20, _strHeight+30); //名字
                //end
                
                //电话
                _this.ctx.setFillStyle(_this.TitleColor);
                _this.ctx.setFontSize(uni.upx2px(28));
                _this.ctx.fillText(_this.phone, header[0]+20, _strHeight+55); //电话
                //end
                
                //添加二维码
                // _strHeight += uni.upx2px(20);
                _this.ctx.drawImage(_QrCode.path, r[0] - q[0] + C_P, _strHeight, q[0], q[1]);
                //添加二维码 end
                
                //延迟后渲染至canvas上
                setTimeout(function() {
                    _this.ctx.draw(true,(ret)=>{
                        _this.getNewImage();
                    });
                }, 600);
            },
            async getImageInfo({ imgSrc }) {
                return new Promise((resolve, errs) => {
                    uni.getImageInfo({
                        src: imgSrc,
                        success: function(image) {
                            resolve(image);
                        },
                        fail(err) {
                            errs(err);
                        }
                    });
                });
            },
            
            /*
             *  参数说明
             *  ctx Canvas实例
             *  img 图片地址
             *   x  x轴坐标
             *   y  y轴坐标
             *   r  圆形半径
             */
             circleImgOne(ctx, img, x, y, r) {
                 // 如果在绘制图片之后还有需要绘制别的元素，需启动 save() 、restore() 方法，否则 clip() 方法会导致之后元素都不可见
                 //    save()：保存当前 Canvas 画布状态
                 // restore()：恢复到保存时的状态
 
                 ctx.save();
                 let d = r * 2;
                 let cx = x + r;
                 let cy = y + r;
                 ctx.arc(cx, cy, r, 0, 2 * Math.PI);
                 ctx.strokeStyle = '#FFFFFF'; // 设置绘制圆形边框的颜色
                 ctx.stroke(); // 绘制出圆形，默认为黑色，可通过 ctx.strokeStyle = '#FFFFFF'， 设置想要的颜色
                 ctx.clip();
                 ctx.drawImage(img, x, y, d, d);
                 ctx.restore();
             },
            getNewImage(){
                const _this = this;
                uni.canvasToTempFilePath({
                    canvasId: _this.CanvasID,
                    quality: 1,
                    complete: (res) => {
                    }
                },this);
            },
            savePoster(){ //保存海报
                const that = this;
                uni.canvasToTempFilePath({
                  canvasId: that.CanvasID,
                  success: function (res) {
                    uni.saveImageToPhotosAlbum({
                      filePath: res.tempFilePath,
                      success(result) {
                        uni.showToast({
                          title: '图片保存成功',
                          icon: 'success',
                          duration: 2000
                        })
                      }
                    })
                  }
                })	
            }
		}
	}
</script>

<style lang="scss" scoped>
	.adviserPage{
        min-height: 100vh;
        overflow: hidden;
        .saveBtn{
            margin: 30rpx;
            background: $theme-color;
            color: #FFFFFF;
            &::after{
                border: none;
            }
        }
    }
</style>
